class ProblemsController < ApplicationController
  include Authorizer
  layout 'standart'
  before_filter :login_required ,:except => [:show, :description]

  def new
    @contests_options = {}
    Contest.all.map {|c| @contests_options[c.name] = c.contest_id}
    if params[:problem] && params[:problem] != ""
        @problem = Problem.new(params[:problem])
    else
        @problem = Problem.new
    end
  end

public
  def create
    @problem = Problem.new(params[:problem])
    @problem.description = params[:description]
    @problem.tests = params[:tests]
    @problem.answers = params[:answers]
    # Това не се чупи, когато има грешка. **Голям** проблем!

    #redirect_to :controller => :problems, :action => :show, :id => 3
    #return
    if @problem.save
      flash[:notice] = "Problem Added successfully!"
      redirect_to :controller => :problems, :action => :show, :id => @problem.problem_id
    else
      flash[:error] = "Could not create the problem"
      # TODO: Измисли работещ начин да се направи това.
      redirect_to :controller => :problems, :action => :new#, :problem => params[:problem]
        #:description => params[:description],
        #:tests => params[:tests],
        #:answers => params[:answers]

      #render :action => :new, :contests_options => params[:contests_options], :problem => @problem
    end
  end

  def edit 
    @problem = Problem.find_by_problem_id(params[:id])
  end

  def show
    @problem = Problem.find_by_problem_id(params[:id])
  end

  def update
    @problem = Problem.find_by_problem_id(params[:id])
    @problem.name = params[:problem][:name]
    @problem.time_limit = params[:problem][:time_limit]
    @problem.letter = params[:problem][:letter]
    @problem.description = params[:description] if params[:description].class != String
    @problem.tests = params[:tests] if params[:tests].class != String
    @problem.answers =params[:answers] if params[:answers].class != String    
    if @problem.save
      flash[:notice] = "Problem edited successully!"
      redirect_to :controller => :spoj1_admin,:action => :index
    else
      render :action => :edit
    end
  end

  def description
    problem = Problem.find_by_problem_id params[:id]#params[:problem]
    unless problem.description
      @problem = problem
      flash[:error] = "No description found"
      redirect_to :back
    else
      send_file(problem.description, :disposition => 'attachment')
    end

  end


  private
  def add_error message
    if flash[:error]
      flash[:error] += "<br>" + message
    else
      flash[:error] = message
    end
  end
  
end
